package cn.ug.activity.web.controller;

import cn.ug.activity.bean.BonusBean;
import cn.ug.activity.bean.BonusStrategyBean;
import cn.ug.activity.mapper.entity.BonusStrategy;
import cn.ug.activity.mapper.entity.ProductBonusMapping;
import cn.ug.activity.service.BonusService;
import cn.ug.activity.service.CouponMemberService;
import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.BonusTypeEnum;
import cn.ug.feign.MemberAccountService;
import cn.ug.feign.MemberGoldService;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("bonus")
public class BonusController extends BaseController {
    @Autowired
    private BonusService bonusService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private CouponMemberService couponMemberService;
    @Autowired
    private MemberGoldService memberGoldService;
    @Autowired
    private MemberAccountService memberAccountService;

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        BonusBean entity = bonusService.get(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     *
     * @param userId  会员id
     * @param productId  产品id
     * @param payTotalAmount  投资金额
     * @return
     */
    @PostMapping("/give")
    public SerializeObject giveProductBonus(String userId, String productId, double payTotalAmount) {
        SerializeObject<MemberUserBean> bean = memberUserService.findById(userId);
        if(null == bean || bean.getCode() != ResultType.NORMAL || bean.getData() == null) {
            Ensure.that(true).isTrue("22000008");
        }
        ProductBonusMapping productBonusMapping = bonusService.findByProductId(productId);
        if (productBonusMapping == null || StringUtils.isBlank(productBonusMapping.getBonusId())) {
            return new SerializeObjectError("22000009");
        }
        BonusBean bonus = bonusService.get(productBonusMapping.getBonusId());
        if (bonus == null) {
            return new SerializeObjectError("22000009");
        }
        List<BonusStrategy> strategies = bonusService.listStrategies(productBonusMapping.getBonusId());
        if (strategies == null || strategies.size() == 0) {
            return new SerializeObjectError("22000009");
        }
        if (giveProductBouns(bonus, strategies, payTotalAmount, bean.getData().getId())) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    public boolean giveProductBouns(BonusBean bonus, List<BonusStrategy> strategies, double principal, String userId) {
        /*int index = 0;
        for (BonusStrategy strategy : strategies) {
            if (principal >= strategy.getQuota()) {
                index++;
            } else {
                break;
            }
        }
        if (index > 0) {
            BonusStrategy strategy = strategies.get(index - 1);
            if (strategy != null) {
                if (bonus.getType() == BonusTypeEnum.INTEREST.getType() || bonus.getType() == BonusTypeEnum.KICKBACK.getType()) {
                    String couponId = strategy.getCouponId();
                    return couponMemberService.giveCoupon(userId, couponId);
                } else if (bonus.getType() == BonusTypeEnum.CASH.getType()) {
                    double amount = strategy.getAmount();
                    BigDecimal decimal = new BigDecimal(amount);
                    SerializeObject bean = memberAccountService.inviteReturnCash(userId, decimal, TradeType.REBATE.getValue());
                    if(null == bean || bean.getCode() != ResultType.NORMAL) {
                        return false;
                    }
                } else if (bonus.getType() == BonusTypeEnum.GOLD.getType()) {
                    double amount = strategy.getAmount();
                    BigDecimal decimal = new BigDecimal(amount);
                    SerializeObject bean = memberGoldService.investRebate(userId, decimal, TradeType.INVITATION_BACK.getValue());
                    if(null == bean || bean.getCode() != ResultType.NORMAL) {
                        return false;
                    }
                } else ;
            }
        }*/
        return true;
    }

    @RequiresPermissions("activity:bonus:save")
    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, BonusBean entity, String strategy) {
        if(null == entity || StringUtils.isBlank(entity.getName())) {
            return new SerializeObjectError("22000001");
        }
        if (StringUtils.isBlank(strategy)) {
            return new SerializeObjectError("22000010");
        }
        try {
            List<BonusStrategyBean> strategies = JSON.parseArray(strategy, BonusStrategyBean.class);
            entity.setStrategies(strategies);
        } catch (Exception e) {
            return new SerializeObjectError("00000002");
        }
        if (bonusService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("activity:bonus:delete")
    @PutMapping
    public SerializeObject delete(@RequestHeader String accessToken, String[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (bonusService.removeInBatch(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("activity:bonus:status")
    @PutMapping(value = "/status")
    public SerializeObject enable(@RequestHeader String accessToken, Integer status, String[] id) {
        status = status == null ? 1 : status;
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (bonusService.modifyStatus(id, status)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("activity:bonus")
    @GetMapping(value = "/list")
    public SerializeObject<DataTable<BonusBean>> list(@RequestHeader String accessToken, Page page, String name, Integer type) {
        name = UF.toString(name);
        type = type == null ? 0 : type;
        int total = bonusService.countRecords(name, type);
        page.setTotal(total);
        if (total > 0) {
            List<BonusBean> list = bonusService.listRecords(name, type, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<BonusBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<BonusBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<BonusBean>()));
    }

    @RequiresPermissions("activity:bonus")
    @GetMapping(value = "/display/list")
    public SerializeObject<List<BonusBean>> list(@RequestHeader String accessToken) {
        List<BonusBean> list = bonusService.listUsableBonus();
        return new SerializeObject<>(ResultType.NORMAL, list);
    }
}
